package com.yanyu.init.utils;

import com.yanyu.init.common.ErrorCode;
import com.yanyu.init.config.EmailConfig;
import com.yanyu.init.exception.BusinessException;
import org.springframework.core.io.ClassPathResource;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;

import javax.mail.MessagingException;
import javax.mail.internet.MimeMessage;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.text.MessageFormat;
import java.util.Random;

public class EmailUtils {

    private static final JavaMailSender mailSender = SpringContextUtils.getBean(JavaMailSender.class);

    private static final EmailConfig emailConfig = SpringContextUtils.getBean(EmailConfig.class);

    /**
     * 注册验证
     *  @param receiver 接收者
     * @param code     验证码
     * @param timeOut  失效时间
     */
    public static void sendEmailCode(String receiver, String code, long timeOut) {
        MimeMessage message = mailSender.createMimeMessage();
        try {
            MimeMessageHelper helper = new MimeMessageHelper(message, true);
            helper.setFrom(emailConfig.getUsername());
            helper.setSubject("注册验证");
            helper.setText(buildContent("注册验证", code, timeOut), true);
            helper.setTo(receiver);
            mailSender.send(message);
        } catch (MessagingException e) {
            throw new BusinessException(ErrorCode.OPERATION_ERROR, "邮件发送失败...");
        }
    }

    public static String buildContent(String title, String code, long timeOut) {
        ClassPathResource resource = new ClassPathResource("templates/mail.ftl");
        InputStream inputStream = null;
        BufferedReader fileReader = null;
        StringBuilder buffer = new StringBuilder();
        String line;
        try {
            inputStream = resource.getInputStream();
            fileReader = new BufferedReader(new InputStreamReader(inputStream));
            while ((line = fileReader.readLine()) != null) {
                buffer.append(line);
            }
        } catch (Exception e) {
            throw new BusinessException(ErrorCode.SYSTEM_ERROR, "邮件模板读取失败...");
        } finally {
            if (fileReader != null) {
                try {
                    fileReader.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (inputStream != null) {
                try {
                    inputStream.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return MessageFormat.format(buffer.toString(), title, code, timeOut);
    }

    /**
     * 生成随机验证码
     *
     * @param length 随机验证码长度
     * @return 随机验证码
     */
    public static String generateRandomCode(int length) {
        String characters = "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";
        StringBuilder code = new StringBuilder();
        Random random = new Random();
        for (int i = 0; i < length; i++) {
            int index = random.nextInt(characters.length());
            code.append(characters.charAt(index));
        }
        return code.toString();
    }
}
